package com.fengwk.support.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.ObjectUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

/**
 * 自定义 httpsession
 * @author fengwk
 * @version 创建时间:2018年1月9日 下午11:03:41
 */
public class CustomHttpSessionFilter implements Filter {
	
	private static final Logger LOG = LoggerUtils.getLogger(CustomHttpSessionFilter.class);
	
	private static ServletContext servletContext;
	private boolean openSession;
	
	/**
	 * init之后将创建servletContext
	 * @return
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取servletContext
		servletContext = filterConfig.getServletContext();
		// 关闭session
		if(ObjectUtils.equals(filterConfig.getInitParameter("openSession"), "true")) {
			this.openSession = true;
		}else {
			this.openSession = false;
			LOG.info("[" + CustomHttpSessionFilter.class + "] 禁用httpsession");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		CustomHttpServletRequestWrapper customHttpServletRequestWrapper = new CustomHttpServletRequestWrapper((HttpServletRequest) request, openSession);
		chain.doFilter(customHttpServletRequestWrapper, response);
	}

	@Override
	public void destroy() {
		// nothing to do
	}
	
	public static class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {

		private HttpServletRequest request;
		
		private boolean openSession = true;
		
		public CustomHttpServletRequestWrapper(HttpServletRequest request) {
			super(request);
			this.request = request;
		}
		
		public CustomHttpServletRequestWrapper(HttpServletRequest request, boolean openSession) {
			this(request);
			this.openSession = openSession;
		}
		
		/**
		 * 创建一个可用session,无论openSession值为如何
		 * @return
		 */
		public HttpSession createSession() {
			return super.getSession(true);
		}
		
		/**
		 * 获取真实request对象
		 * @return
		 */
		public HttpServletRequest getRealRequest() {
			return request;
		}
		
		@Override
		public HttpSession getSession(boolean create) {
			if(openSession) {
				return super.getSession(create);
			}
			return null;
		}

		@Override
		public HttpSession getSession() {
			return getSession(true);
		}
		
	}
	
}
